#include <func.h>

#define N 10000000

typedef struct {
    int num;
    pthread_mutex_t mutex;
} data_t;

void *pthread_func(void *p)
{
    data_t *d = (data_t *)p;
    for (int i = 0; i < N; i ++)
    {
        pthread_mutex_lock(&d->mutex);
        d->num ++;
        pthread_mutex_unlock(&d->mutex);
    }
}

// 线程锁实现多线程各加一千万
int main()
{
    pthread_mutexattr_t mutex_attr; // 定义一个锁属性
    pthread_mutexattr_init(&mutex_attr); // 初始化锁属性
    pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP); // 设置为嵌套锁，可以加锁多次

    pthread_t pthid;
    data_t d;
    d.num = 0;

    int ret = pthread_mutex_init(&d.mutex, &mutex_attr); // 锁初始化，设置锁属性
    ERROR_CHECK(ret, -1, "pthread_mutex_init");

    ret = pthread_create(&pthid, NULL, pthread_func, (void *)&d.num);
    ERROR_CHECK(ret, -1, "pthread_create");

    for (int i = 0; i < N; i ++)
    {
        pthread_mutex_lock(&d.mutex); // 加锁
        d.num ++;
        pthread_mutex_unlock(&d.mutex); // 解锁
    }
        

    ret = pthread_join(pthid, NULL);
    ERROR_CHECK(ret, -1, "pthread_join");

    printf("num = %d\n", d.num);

    ret = pthread_mutex_destroy(&d.mutex); // 销毁锁
    ERROR_CHECK(ret, -1, "pthread_mutex_destroy");

    return 0;
}